﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.CodeDom;
using System.Threading;

namespace CodeDomHelper.CodeDom.Statement
{

    /// <summary>
    /// Represents the locking of a cursor to an hourglass until the end of the contained statements.
    /// </summary>
    /// <example>Output example:<code>
    ///	System.Windows.Forms.Cursor cursor0 = this.Cursor;
    ///
    ///	try
    ///	{
    ///		this.Cursor = System.Windows.Forms.Cursors.WaitCursor;
    ///		
    ///		// More code here...
    ///	}
    ///	finally
    ///	{
    ///		this.Cursor = cursor0;
    ///	}
    ///	</code></example>
    [Serializable, CLSCompliant(true)]
    public class CodePatternLock : CodeTryCatchFinallyStatement
    {

        /// <summary>
        /// Initializes a new instance of the CodePatternCursorLock class.
        /// </summary>
        /// <param name="formReference">The reference to the form object whose cursor should be locked.</param>
        /// <param name="statements">The statements during which the cursor is locked.</param>
        public CodePatternLock(CodeExpression cursor, params CodeStatement[] statements)
        {


            // Add cursor lock.
            TryStatements.Add
            (
                new CodeMethodInvokeExpression
                (
                    new CodeMethodReferenceExpression
                    (
                        new CodeTypeReferenceExpression(typeof(System.Threading.Monitor)),
                        "Enter"
                    ),
                    cursor
                )
            );

            // Add cursor release.
            FinallyStatements.Add
            (
                new CodeMethodInvokeExpression
                (
                    new CodeMethodReferenceExpression
                    (
                        new CodeTypeReferenceExpression(typeof(System.Threading.Monitor)),
                        "Exit"
                    ),
                    cursor
                )
            );

            // Add contained statements.
            TryStatements.AddRange(statements);

        }

    }

}
